package com.lucaswangdev.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 获取SQLSession对象的工具类
 */
public class SqlSessionUtils {

    private static SqlSession sqlSession;

    static {
        try {
            //加载Mybatis的核心配置文件
            InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //获取SQLSession对象, 执行sql语句
            sqlSession = sqlSessionFactory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 提供一个方法, 返回SQLSession对象
     */
    public static SqlSession getSqlSession(){
        return sqlSession;
    }
}
